package br.uefs.cedoc.db;



import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;



import br.uefs.cedoc.util.ConfigDB;

import com.javaexchange.dbConnectionBroker.DbConnectionBroker;

/**
 * Classe responsavel por estabelecer a conexao com o banco de dados
 * @author SMAU
 *
 */
public class DBController
{
	private static DBController instance;
	private DbConnectionBroker myBroker;
	

	public DBController()
	{
		try {
			int minCon = ConfigDB.DB_MIN_CON;
			int maxCon = ConfigDB.DB_MAX_CON;
			String driver = ConfigDB.DB_DRIVER;
			String url = ConfigDB.DB_SERVER_HOST;
			String user = ConfigDB.DB_USERNAME;
			String password = ConfigDB.DB_PASSWORD;
			String logFile = ConfigDB.DB_LOG +System.currentTimeMillis()+".log";
			String dir = logFile.substring(0, logFile.lastIndexOf("/"));
			new File(dir).mkdirs();
			int debugSqlPool = 2;

/* driver utilizado, url para conectar com o banco, usario do banco, senha, quantidade minima de conexao,
quantidade maxima de conexao,  path Arquivo de LOG,  quant. de vez q o pool vai ser reiniciado, debug 0 - Sem Debug; 1- Error; 2-All*/
			
		
			myBroker = new DbConnectionBroker(driver, url, user, password,
					minCon, maxCon, logFile, 1, false, 60,
					debugSqlPool);
			System.out.println("DBController> Pool de conexoes criado com sucesso!");
			
		}
		catch (Exception e) {
			System.out.println("DBController> Erro na criacao do Pool");
			System.out.println("Erro : " + e.getMessage());
			System.out.println("Erro : " + e.getClass());
			e.printStackTrace();
		}

	}


	public synchronized static DBController getInstance() {
		if( instance == null ) {
			instance = new DBController();
		}
		return instance;
	}

	public Connection getConnection() throws SQLException {
		return myBroker.getConnection();
	}

	public void closeAll(Connection iConn, ResultSet rs, Statement st) {
		try {
			if( st != null ) {
				st.close();
			}
			if( rs != null ) {
				rs.close();
			}
			if( iConn != null ) {
				//iConn.close();
				myBroker.freeConnection(iConn);
				//iConn.close();
			}
		}
		catch (Exception e) {
			System.out.println("Erro no fechamento");
		}
	}

	public static void main(String[] args) throws SQLException {
		Connection conn = DBController.getInstance().getConnection();
		
		System.out.print("Conectou: " + conn);
		DBController.getInstance().closeAll(conn, null, null);
	}
}
